package com.scs.application.modules.wm.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.ReagentTeam;
import com.scs.application.modules.base.mapper.MatrMapper;
import com.scs.application.modules.base.service.ReagentTeamService;
import com.scs.application.modules.purchase.enums.PurchaseType;
import com.scs.application.modules.wm.entity.Stock;
import com.scs.application.modules.wm.entity.TertiaryStock;
import com.scs.application.modules.wm.entity.WorkOrder;
import com.scs.application.modules.wm.entity.WorkOrderItem;
import com.scs.application.modules.wm.mapper.TertiaryStockMapper;
import com.scs.application.modules.wm.service.StockService;
import com.scs.application.modules.wm.service.TertiaryStockService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 三级库存 服务实现类
 * </p>
 */
@Service
public class TertiaryStockServiceImpl extends BaseServiceImpl<TertiaryStockMapper, TertiaryStock> implements TertiaryStockService {

    @Resource
    StockService stockService;

    @Resource
    ReagentTeamService reagentTeamService;

    @Resource
    MatrMapper matrMapper;

    @Override
    public void addStock(WorkOrder workOrder, List<WorkOrderItem> workOrderItems) {
        if (CollectionUtils.isEmpty(workOrderItems)) { return; }
        List<TertiaryStock> list = new ArrayList<>();
        // 对入库明细过滤，只保留试剂
        List<String> matrIds = workOrderItems.stream().map(WorkOrderItem::getMatrId).collect(Collectors.toList());
        List<Matr> matrList = matrMapper.selectList(Wrappers.<Matr>query().in("id", matrIds).eq("base_type", PurchaseType.REAGENT.getKey()));
        workOrderItems = workOrderItems.stream().filter(item -> matrList.stream().anyMatch(matr -> matr.getId().equals(item.getMatrId()))).collect(Collectors.toList());

        // 添加三级库库存
        List<String> stockIds = workOrderItems.stream().map(WorkOrderItem::getStockId).collect(Collectors.toList());
        workOrderItems.forEach(workOrderItem -> stockIds.stream().filter(sid -> sid.equals(workOrderItem.getStockId())).forEach(stockId->{
            Stock stock = stockService.getById(workOrderItem.getStockId());
            if (stock == null) {
                throw new BusinessException("未能按照提供的StockId检索到库存记录，stockId：" + workOrderItem.getStockId());
            }

            ReagentTeam reagentTeam = reagentTeamService.getById(workOrder.getReagentTeamId());
            TertiaryStock tertiaryStock = new TertiaryStock();
            BeanUtils.copyProperties(stock, tertiaryStock);
            tertiaryStock.setInTime(new Date())
                    .setReagentTeamId(workOrder.getReagentTeamId())
                    .setReagentTeamName(reagentTeam.getName())
                    .setDeptId(workOrder.getDeptId())
                    .setDeptName(workOrder.getDeptName())
                    .setId(null);
            list.add(tertiaryStock);
        }));

        // 先删除现有库存再添加新的库存，避免sn重复
        List<String> snList = workOrderItems.stream().map(WorkOrderItem::getSn).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(snList)) {
            this.remove(Wrappers.<TertiaryStock>update().in("sn", snList));
        }
        this.saveBatch(list);
    }

    @Override
    public TertiaryStock getStockByUniqueCode(String uniqueCode) {
        if (StringUtils.isBlank(uniqueCode)) {
            throw new BusinessException("唯一码不能为空");
        }
        // 判断唯一码类型
        return this.getOne(stockService.getStockQueryWrapper(uniqueCode));
    }
}
